package com.inspectortime.webapp.inspector;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.util.HttpSessionUtils;
import com.inspectortime.webapp.util.LoggedInUserNotFoundException;

public class EditLogoController extends SimpleFormController {

	private Log log = LogFactory.getLog(EditLogoController.class);
	private Repository repository;

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws ServletException, IOException, LoggedInUserNotFoundException {

		/*
		String inspectorCompanyShortName = RequestPathUtils
				.extractInspectorCompanyShortNameFromPath(request);
		InspectorCompany inspectorCompany = repository
				.findInspectorCompanyByShortName(inspectorCompanyShortName);
		*/
		
		InspectorCompany inspectorCompany = HttpSessionUtils.retrieveLoggedInCompany(request, repository);

		EditLogoForm form = (EditLogoForm) command;
		
		//MultipartFile multipartFile = multipartRequest.getFile("file");
		byte[] bytes = form.getFile();
		inspectorCompany.setLogoImage(bytes);
		//inspectorCompany.readLogoImageFrom(multipartFile.getInputStream());
		inspectorCompany.save();

		// Delay a bit to allow time for the file to copy
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			throw new RuntimeException("Wait interrupted", e);
		}

		return new ModelAndView(this.getSuccessView());
	}

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws ServletException {
		// to actually be able to convert Multipart instance to byte[]
		// we have to register a custom editor (in this case the
		// ByteArrayMultipartEditor
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
		// now Spring knows how to handle multipart object and convert them
	}
	
	/**
	 * @deprecated may be useful if we need to retain image name or extension 
	 * @param multipartFile
	 * @param dirPath
	 * @return Filename
	 */
	public static String saveMultipartFile(MultipartFile multipartFile,
			String dirPath, boolean uppercase, String newFileName)
			throws IOException {
		if (multipartFile != null) {

			// Make sure user explicitly uploaded a new file
			String convertedFileName = null;
			if (newFileName == null && uppercase) {
				convertedFileName = multipartFile.getOriginalFilename()
						.toUpperCase();
			} else if (newFileName == null) {
				convertedFileName = multipartFile.getOriginalFilename();
			} else {
				convertedFileName = newFileName;
			}
			File filePath = new File(dirPath);
			if (!filePath.exists()) {
				filePath.mkdirs();
			}

			String fileName = fileName = dirPath + File.separator
					+ convertedFileName;

			File file = new File(fileName);
			if (file.exists()) {
				file.delete();
			}
			multipartFile.transferTo(file);
			return convertedFileName;
		}
		return null;
	}

	public void setRepository(Repository repository) {
		this.repository = repository;
	}
}
